#include "simulator_view_model.h"
#include "kernel/agv/agv_entity.h"
#include "kernel/task/task_types.h"
#include <QTimer>

namespace presentation {
namespace viewmodels {

SimulatorViewModel::SimulatorViewModel(QObject* parent)
    : BaseViewModel(parent)
    , m_simulationService(nullptr)
    , m_vehicleService(nullptr)
    , m_taskService(nullptr)
{
}

SimulatorViewModel::SimulatorViewModel(
    std::shared_ptr<application::simulation::SimulationService> simulationService,
    application::vehicle::VehicleService* vehicleService,
    application::task::TaskService* taskService,
    QObject* parent)
    : BaseViewModel(parent)
    , m_simulationService(simulationService)
    , m_vehicleService(vehicleService)
    , m_taskService(taskService)
{
    if (m_simulationService) {
        m_isEnabled = m_simulationService->isEnabled();
    }
}

void SimulatorViewModel::initialize() {
    if (!m_simulationService) {
        handleError("仿真服务未初始化");
        return;
    }

    // 连接信号
    connectSignals();

    // 初始化状态
    if (m_simulationService->engine()) {
        m_isPlaying = m_simulationService->engine()->isPlaying();
        m_isPaused = m_simulationService->engine()->isPaused();
        m_simulationTime = m_simulationService->engine()->getSimulationTime();
        m_timeScale = m_simulationService->engine()->getTimeScale();
    }

    // 更新初始统计数据
    updateKpiMetrics();

    setInitialized(true);
    emit simulationStateChanged();
    emit simulationTimeChanged();
    emit timeScaleChanged();
    emit kpiChanged();
}

void SimulatorViewModel::cleanup() {
    // 断开所有信号连接
    if (m_simulationService) {
        disconnect(m_simulationService.get(), nullptr, this, nullptr);
    }
    if (m_vehicleService) {
        disconnect(m_vehicleService, nullptr, this, nullptr);
    }
    setInitialized(false);
}

void SimulatorViewModel::connectSignals() {
    // 连接仿真引擎信号
    if (m_simulationService && m_simulationService->engine()) {
        auto* engine = m_simulationService->engine();

        connect(engine, &application::simulation::SimulationEngine::simulationTimeChanged,
                this, &SimulatorViewModel::onSimulationTimeChanged);

        connect(engine, &application::simulation::SimulationEngine::simulationStarted,
                this, [this]() {
                    m_isPlaying = true;
                    m_isPaused = false;
                    emit simulationStateChanged();
                });

        connect(engine, &application::simulation::SimulationEngine::simulationPaused,
                this, [this]() {
                    m_isPaused = true;
                    emit simulationStateChanged();
                });

        connect(engine, &application::simulation::SimulationEngine::simulationStopped,
                this, [this]() {
                    m_isPlaying = false;
                    m_isPaused = false;
                    emit simulationStateChanged();
                });
    }

    // 连接车辆服务信号
    if (m_vehicleService) {
        connect(m_vehicleService, &application::vehicle::VehicleService::vehicleStatusChanged,
                this, &SimulatorViewModel::onVehicleStatusChanged);

        connect(m_vehicleService, &application::vehicle::VehicleService::vehicleRegistered,
                this, [this](int) { updateVehicleStatistics(); });

        connect(m_vehicleService, &application::vehicle::VehicleService::vehicleUnregistered,
                this, [this](int) { updateVehicleStatistics(); });
    }

    // TaskService 不是 QObject，无法连接信号
    // 统计数据通过定时器更新

    // 定时更新 KPI（每秒更新一次）
    auto* kpiTimer = new QTimer(this);
    connect(kpiTimer, &QTimer::timeout, this, &SimulatorViewModel::updateKpiMetrics);
    kpiTimer->start(1000);
}

// ==================== 属性访问器 ====================

QString SimulatorViewModel::duration() const {
    int totalSeconds = static_cast<int>(m_simulationTime);
    int hours = totalSeconds / 3600;
    int minutes = (totalSeconds % 3600) / 60;
    int seconds = totalSeconds % 60;

    if (hours > 0) {
        return QString("%1:%2:%3")
            .arg(hours, 2, 10, QChar('0'))
            .arg(minutes, 2, 10, QChar('0'))
            .arg(seconds, 2, 10, QChar('0'));
    } else {
        return QString("%1:%2")
            .arg(minutes, 2, 10, QChar('0'))
            .arg(seconds, 2, 10, QChar('0'));
    }
}

double SimulatorViewModel::taskCompletionRate() const {
    int totalTasks = m_completedTaskCount + m_failedTaskCount;
    if (totalTasks == 0) {
        return 0.0;
    }
    return (static_cast<double>(m_completedTaskCount) / totalTasks) * 100.0;
}

// ==================== 仿真控制命令 ====================

void SimulatorViewModel::play() {
    if (!m_simulationService || !m_isEnabled) {
        handleError("仿真服务未启用");
        return;
    }

    m_simulationService->play();
}

void SimulatorViewModel::pause() {
    if (!m_simulationService || !m_isEnabled) {
        handleError("仿真服务未启用");
        return;
    }

    m_simulationService->pause();
}

void SimulatorViewModel::resume() {
    if (!m_simulationService || !m_isEnabled) {
        handleError("仿真服务未启用");
        return;
    }

    m_simulationService->resume();
}

void SimulatorViewModel::stop() {
    if (!m_simulationService || !m_isEnabled) {
        handleError("仿真服务未启用");
        return;
    }

    m_simulationService->stop();

    // 重置统计数据
    resetStatistics();
}

void SimulatorViewModel::step(double deltaTime) {
    if (!m_simulationService || !m_isEnabled) {
        handleError("仿真服务未启用");
        return;
    }

    m_simulationService->step(deltaTime);
}

void SimulatorViewModel::setTimeScale(double scale) {
    if (!m_simulationService || !m_isEnabled) {
        handleError("仿真服务未启用");
        return;
    }

    // 限制范围 0.1x ~ 10x
    double clampedScale = qBound(0.1, scale, 10.0);

    if (qAbs(m_timeScale - clampedScale) > 0.01) {
        m_timeScale = clampedScale;
        m_simulationService->setTimeScale(clampedScale);
        emit timeScaleChanged();
    }
}

void SimulatorViewModel::resetStatistics() {
    m_completedTaskCount = 0;
    m_failedTaskCount = 0;
    m_conflictCount = 0;

    emit kpiChanged();
}

void SimulatorViewModel::loadScenario(const QString& scenarioName) {
    m_scenarioName = scenarioName;
    emit scenarioChanged();

    // TODO: 实现场景加载逻辑
    // 1. 读取场景配置文件
    // 2. 重置仿真环境
    // 3. 创建仿真车辆
    // 4. 加载任务序列
}

void SimulatorViewModel::resetSimulationVehicles() {
    if (!m_simulationService || !m_simulationService->isEnabled()) {
        handleError("仿真服务未启用，无法重置车辆");
        return;
    }

    m_simulationService->resetVehiclesToInitialState();
}

// ==================== 槽函数 ====================

void SimulatorViewModel::onSimulationTimeChanged(double time) {
    if (qAbs(m_simulationTime - time) > 0.01) {
        m_simulationTime = time;
        emit simulationTimeChanged();
    }
}

void SimulatorViewModel::onSimulationStateChanged(bool isPlaying, bool isPaused) {
    bool changed = false;

    if (m_isPlaying != isPlaying) {
        m_isPlaying = isPlaying;
        changed = true;
    }

    if (m_isPaused != isPaused) {
        m_isPaused = isPaused;
        changed = true;
    }

    if (changed) {
        emit simulationStateChanged();
    }
}

void SimulatorViewModel::onVehicleStatusChanged(int agvNumber) {
    Q_UNUSED(agvNumber);
    // 车辆状态变化时更新统计数据
    updateVehicleStatistics();
}

void SimulatorViewModel::updateKpiMetrics() {
    updateVehicleStatistics();
    updateTaskStatistics();
}

void SimulatorViewModel::updateVehicleStatistics() {
    if (!m_vehicleService) {
        return;
    }

    auto vehicles = m_vehicleService->getAllVehicles();

    int onlineCount = 0;
    int idleCount = 0;

    for (const auto* agv : vehicles) {
        if (agv->isOnline()) {
            onlineCount++;

            // 空闲定义：在线 + 不在充电 + 不在执行任务
            if (!agv->isCharging() && !agv->isBusy() && !agv->isControlledByDispatcher()) {
                idleCount++;
            }
        }
    }

    bool changed = false;

    if (m_onlineVehicleCount != onlineCount) {
        m_onlineVehicleCount = onlineCount;
        changed = true;
    }

    if (m_idleVehicleCount != idleCount) {
        m_idleVehicleCount = idleCount;
        changed = true;
    }

    if (changed) {
        emit kpiChanged();
    }
}

void SimulatorViewModel::updateTaskStatistics() {
    if (!m_taskService) {
        return;
    }

    // 使用 TaskService 的 getActiveTaskIds() 和 getTaskState()
    auto activeTaskIds = m_taskService->getActiveTaskIds();

    int completedCount = 0;
    int failedCount = 0;

    for (const auto& chainId : activeTaskIds) {
        const auto* state = m_taskService->getTaskState(chainId);
        if (!state) {
            continue;
        }

        // TaskChainStatus 仅包含执行阶段状态，完成/失败需要结合 finished 与 Error 状态判断
        const bool isCompleted =
            state->finished &&
            state->status == kernel::task::TaskChainStatus::Ok;
        const bool isFailed =
            state->status == kernel::task::TaskChainStatus::Error;

        if (isCompleted) {
            completedCount++;
        } else if (isFailed) {
            failedCount++;
        }
    }

    bool changed = false;

    if (m_completedTaskCount != completedCount) {
        m_completedTaskCount = completedCount;
        changed = true;
    }

    if (m_failedTaskCount != failedCount) {
        m_failedTaskCount = failedCount;
        changed = true;
    }

    // TODO: 冲突计数需要与多车占道系统集成
    // m_conflictCount = ...;

    if (changed) {
        emit kpiChanged();
    }
}

} // namespace viewmodels
} // namespace presentation
